package com.decent.ejfadmin.ebitg.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ContentDisposition;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.decent.ejfadmin.common.bean.MessageBean;
import com.decent.ejfadmin.ebitg.entity.SupCert;
import com.decent.ejfadmin.ebitg.mapper.SupCertMapper;
import com.decent.ejfadmin.user.bean.Const;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author Adrain
 * @since 2024-10-17
 */
@RestController
@RequestMapping("userCert")
@Slf4j
public class UserCertController {
	private static final String contractDir = "/usr/local/dlk_admin/contract/";

	@Autowired
	private SupCertMapper supCertMapper;

	public UserCertController() {
		File targetDir = new File(contractDir);
		if (targetDir.isFile() || !targetDir.exists()) {
			log.info("create dir={}", contractDir);
			targetDir.mkdirs();
		}

	}

	@PostMapping("uploadContract")
	public MessageBean upload(@RequestPart("file") MultipartFile file, Long userid) throws IOException {
		Subject subject = SecurityUtils.getSubject();
		log.debug("subject={}", subject.getPrincipal());

		if (Objects.isNull(userid) || userid == -1) {
			return MessageBean.fail("请选择上传合同的会员");
		}
		LambdaQueryWrapper<SupCert> queryWrapper = Wrappers.lambdaQuery(SupCert.class);
		queryWrapper.eq(SupCert::getUserId, userid);
		SupCert supCert = supCertMapper.selectOne(queryWrapper);
		if (Objects.isNull(supCert)) {
			return MessageBean.fail("不存在的用户:" + userid);
		}
		Integer successLevel = supCert.getSuccessLevel();
		if (successLevel < 2) {
			return MessageBean.fail("请先完成实名和身份证认证." + userid);
		}
		if (successLevel > 2) {
			log.info("已经进行2级以上认证");
		}
		String contractId = supCert.getContractId();
		if (StringUtils.isNotBlank(contractId)) {
			log.warn("原有合同id[{}]", contractId);
		}

		String contentType = file.getContentType();
		String name = file.getName();
		InputStream inputStream = file.getInputStream();
		String originalFilename = file.getOriginalFilename();
		String targetFilename = generateFilename();
		try (FileOutputStream output = new FileOutputStream(contractDir + targetFilename);) {
			IOUtils.copy(inputStream, output);
		}
		log.info("file{}={},{},{}", targetFilename, contentType, name, originalFilename);
		SupCert supCertDB = SupCert.builder().id(supCert.getId()).contractId(targetFilename)
				.successLevel(Const.LEVEL_THREE).levelState(Const.SUCCESS_CERT).build();
		int r = supCertMapper.updateById(supCertDB);
		if (r == 1) {
			return MessageBean.success("三级认证完成");
		} else {
			return MessageBean.fail("保存合同异常,请联系技术人员!");
		}
	}

	@RequestMapping(value = "/downloadContract")
	public void down(@RequestParam("fileName") String fileName, HttpServletResponse response) {
		try (InputStream inputStream = new FileInputStream(contractDir + fileName);
				ServletOutputStream outputStream = response.getOutputStream();) {
			response.reset();
			response.addHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
			ContentDisposition disposition = ContentDisposition.builder("attachment")
					.filename(new String(URLEncoder.encode(fileName, "UTF-8").getBytes(StandardCharsets.UTF_8),
							StandardCharsets.ISO_8859_1))
					.build();
			response.addHeader("Content-Disposition", disposition.toString());
			byte[] buffer = new byte[1024];
			int len;
			while ((len = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String generateFilename() {
		String randomUUID = UUID.randomUUID().toString() + ".pdf";
		return randomUUID;
	}
}
